package com.funo.main.dao.impl;

import java.util.List;

import org.hibernate.Criteria;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.funo.common.pojo.QueryCondition;
import com.funo.core.base.BaseDao;
import com.funo.main.dao.RoleDao;
import com.funo.main.entities.Role;

/**
 * 角色管理接口实现类
 * 
 * @author zhengjs
 *
 */
@SuppressWarnings("unchecked")
@Repository
public class RoleDaoImpl extends BaseDao<Role, String> implements RoleDao{

	@Override
	public List<Role> pageList(QueryCondition condition) {
		Criteria criteria = super.getCriteria();
		if(condition.containParam("id") && !StringUtils.isEmpty(condition.getParam("id"))){
//			//TODO - tian jia chaxun tiaojian 
//			//criteria.add(Restrictions.eq("id", role.getId());
//			//String hql="from UserRole where ur.user.id=?";
//			String userid=condition.getParam("id");
//			List userRoleList=super.findByHql("from UserRole where user.id = ?", userid);
//			
//			for (int i = 0; i < userRoleList.size(); i++) {
//				UserRole userRole=(UserRole)userRoleList.get(i);
//				String roleId=userRole.getRole().getId();
//				criteria.add(Restrictions.eq("id", roleId));
//			}

			//criteria.add( Restrictions.sqlRestriction("{alias}.id in (select role_id form user_role where user_id = ?)",
					//condition.getParam("id"),Hibernate.STRING)) ;
			
		}
		
		criteria.setFirstResult(condition.getStart());
		criteria.setMaxResults(condition.getLimit());
		
		return super.findByCriteria(criteria);
	}

	@Override
	public Integer count(QueryCondition condition) {
		Criteria criteria = super.getCriteria();
		if(condition.containParam("id") && !StringUtils.isEmpty(condition.getParam("id"))){
			//TODO - tian jia chaxun tiaojian 
//			String hql="select * from UserRole where user.id=?";
//			List userRoleList=super.findBySql(hql, condition.getParam("id"));
//			
//			for (int i = 0; i < userRoleList.size(); i++) {
//				UserRole userRole=(UserRole)userRoleList.get(i);f
//				String roleId=userRole.getRole().getId();
//				criteria.add(Restrictions.eq("id", roleId));
//			}
		}
		
		return super.countByCriteria(criteria);
	}

	@Override
	public Role getRole(String name) {
		List<Role> list = super.findByHql("from Role where name=?", name);
		return list.size()==1?list.get(0):null;
	}

	@Override
	public Role findRoleByName(String name, String id) {

		String hql ="from Role where name = ? and id !=?";

		List<Role> list =super.findByHql(hql, name, id);
		
		return list!=null && list.size()>0?list.get(0):null;	
	}

	@Override
	public List<Role> getRole() {
		return findByHql("from Role order by roleLevel");
	}
}
